
import {Date2} from '../../utils/date2.js'
const app = getApp()
import {UploadOssFile, OssUploadConfig} from '../../utils/image_upload/UploadAliyun.js'
import {getNameFromUrl} from '../../utils/util'

const PAGE_SIZE = 15   //文章每页大小

// pages/family/person.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    family: 0,  //从哪个家族进入
    person: 0,  //当前人的ID
    curr_tab_index: 0,  //当前激活的tab索引， 从0开始
    activeTab: 0,
    attrs: [],  //所有属性和值
    person_scroll_height: 0,  //scroll-view的固定高度，单位像素

    creator_id: 0,
    creator_name: '',  //当前人员添加者

    files: [],
    delete_pic_on: false,  //是否打开预览删除按钮

    //文章参数：
    log_list: [],
    pageNum: 1,   //当前页码
    isLoadEnd: false,   //所有文章是否加载完毕，如果加载完毕就不再加载
    buttons: [{text: '取消'}, {text: '新增'}],
    showDialog: false,
    article_title_focus: false,
    article_title: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('start personal page', options)
    this.setData({
      family: parseInt(options.family),
      person: parseInt(options.person)
    })

    //请求属性信息
    this.refreshAttr()

    this.setData({
      selectFile: this.selectFile.bind(this),
      uplaodFile: this.uplaodFile.bind(this)
    })

    this.BeginLoadArticles()  //加载文章
  },

  refreshAttr: function() {
    app.httpRequest('get_person_vals', {
      family: this.data.family,
      target_person: this.data.person
    }, resObj => {
      console.log('get attr val list: ', resObj)
      this.setData({
        creator_id: resObj.create_person,
        creator_name: resObj.create_person_name
      })

      let res = resObj.vals
      //转化数据格式
      for (let i = 0; i < res.length; i++) {
        if (res[i].fix == 1 && res[i].attr_name == '生日') {
          if (res[i].value.length > 0) {
            let date2 = new Date2()
            let ok = date2.ParseDbDateStr(res[i].value)
            if (!ok) {
              app.showTip('日期格式异常')
            } else {
              res[i].value = date2.FormatShowDate()
            }
          }
        }

        if (res[i].fix == 1 && res[i].attr_name == '性别') {
          res[i].value = res[i].value == "1" ? "男" : "女"
        }
      }

      this.setData({
        attrs: res
      })
    }, res => {
      console.log('get attr val list failed: ', res)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.createSelectorQuery()
    .select('.person_page')
    .fields({
      size: true
    })
    .exec(this.person_init.bind(this))
  },

  person_init(res) {
    const width = res[0].width
    const height = res[0].height
    this.setData({
      person_scroll_height: height
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  onTabClick(e) {
    const index = e.detail.index
    this.setData({ 
      activeTab: index 
    })
  },
  onChange(e) {
    const index = e.detail.index
    this.setData({ 
      activeTab: index 
    })
  },
  bindEditAttr(e) {
    if (this.data.person != 0) {
      wx.navigateTo({
        url: './edit_attr?person=' + this.data.person + '&family=' + this.data.family,
      })
    }
  },

  bindTapPerson(e) {
    this.setData({
      curr_tab_index: 0
    })
  },

  bindTapLog(e) {
    this.setData({
      curr_tab_index: 1
    })
  },

  bindTapPhoto(e) {
    this.setData({
      curr_tab_index: 2
    })

    app.httpRequest('get_person_pic', {
      family: this.data.family,
      target_person: this.data.person
    }, res => {
      console.log('get pics success: ', res)
      this.setData({
        files: res.map(name => { return {url: app.globalConfig.getPicUrl() + '/' + name}; })
      })
    }, res => {
    })
  },

  bindEditAttrValue(e) {
    if (this.data.person != 0) {
      wx.navigateTo({
        url: './edit_attr_value?person=' + this.data.person + '&family=' + this.data.family,
      })
    }
  },

  chooseImage: function (e) {
      var that = this;
      wx.chooseImage({
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          count: 9,
          success: function (res) {
              // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
              console.log('choose files: ', res)
              that.setData({
                  files: that.data.files.concat(res.tempFilePaths)
              });
          }
      })
  },
  previewImage: function(e){
      wx.previewImage({
          current: e.currentTarget.id, // 当前显示图片的http链接
          urls: this.data.files // 需要预览的图片http链接列表
      })
  },
  selectFile(files) {
      console.log('files', files)
      // 返回false可以阻止某次文件上传
  },
  uplaodFile(files) {
      console.log('upload files', files)

      const tempFilePaths = files.tempFilePaths
      // 文件上传的函数，返回一个promise
      return new Promise((resolve, reject) => {
        var length = tempFilePaths.length; //总数
        var count = 0; //第几张
        this.uploadOneByOne(tempFilePaths, count, length, 
          () => {
            //成功
            app.httpRequest('add_person_pic', {
              family: this.data.family,
              target_person: this.data.person,
              pic_names: tempFilePaths.map(url => getNameFromUrl(url))
            }, res => {
              console.log('upload pics success: ', res)
            
            }, res => {
              console.log('upload pics failed: ', res)
            })

            var object = {};
            object['urls'] = tempFilePaths;
            resolve(object)  //执行即返回
          }, () => {
            //失败
            reject('some error.')
          })
    })
  },

  /**
  * 采用递归的方式上传多张, 注意wx.uploadFile不能并发, 还有ui不支持一次上传同时显示成功和失败，所以此函数要么成功，要么失败
  */
 uploadOneByOne(imgPaths, count, length, allSuccCallback, allFailCallback){
    var scope = this;
    wx.uploadFile({
      url: app.globalConfig.getPicEditUrl() + '/file/upload', //仅为示例，非真实的接口地址
      filePath: imgPaths[count],
      name: 'file',
      formData: {
        'key': 'val'
      },
      success:function(e){
        count++;//下一张
        if(count == length){
          //上传完毕，作一下提示
          allSuccCallback()
        }else{
          //递归调用，上传下一张
          scope.uploadOneByOne(imgPaths, count, length, allSuccCallback, allFailCallback);
        }
      },
      fail:function(e){
        //失败了，所有图片都发送失败，删除之前已经发送的
        for (let i = 0; i < count; i++) {
          scope.requestDeletePic(imgPaths[i])
        }
        allFailCallback()
      }
    })
  },

  //从后台删除图片
  requestDeletePic(url) {
    let filename = getNameFromUrl(url)
    if (filename == '') {
      return
    }
    
    wx.request({
      url: app.globalConfig.getPicEditUrl() + '/file/delete',
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded'},
      data: {
        filename: filename
      },
      success: (res) => {
        console.log('delete file success!')
      },
      fail: (res) => {
        console.log('delete file failed!')
      }
    })
  },

  uploadError(e) {
      console.log('upload error', e.detail)
  },
  uploadSuccess(e) {
      console.log('upload success', e.detail)
  },
  deletePic(e) {
    console.log('delete pic :', JSON.stringify(e.detail))
    if (e.detail && e.detail.item && e.detail.item.url) {
      console.log('-----------to delete', e.detail.item.url)

      app.httpRequest('del_person_pic', {
        family: this.data.family,
        target_person: this.data.person,
        pic_name: getNameFromUrl(e.detail.item.url)
      }, res => {
        console.log('delete pics success: ', res)
      }, res => {
        console.log('delete pics failed: ', res)
      })

      this.requestDeletePic(e.detail.item.url)
    }
  },

  changeDeletePicSwitch(e) {
    this.setData({
      delete_pic_on: e.detail.value
    })
  },

  //文章

  //重新加载整个列表
  BeginLoadArticles() {
    this.setData({
      pageNum: 1,
      isLoadEnd: false,
      log_list: [],
      showDialog: false
    })

    app.httpRequest('get_article_list', {
      family: this.data.family,
      target_person: this.data.person,
      page: this.data.pageNum,
      pagesize: PAGE_SIZE
    }, res => {
      console.log('get_article_list success: ', res)
      if (res.length < PAGE_SIZE) {
        this.setData({
          isLoadEnd: true
        })
      }
      this.data.pageNum++
      this.setData({
        log_list: res
      })
    }, res => {
      console.log('get_article_list failed: ', res)
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("reach bottom ...........")
    if (this.data.curr_tab_index != 1) {
      return
    }
    this.timer = setInterval(() => {
      this.onBottom()
    }, 2000)
  },

  //触底响应函数
  onBottom(){
    if (this.data.isLoadEnd) {
      return
    }

    app.httpRequest('get_article_list', {
      family: this.data.family,
      target_person: this.data.person,
      page: this.data.pageNum,
      pagesize: PAGE_SIZE
    }, res => {
      console.log('get_article_list success: ', res)
      if (res.length < PAGE_SIZE) {
        this.setData({
          isLoadEnd: true
        })
      }
      this.data.pageNum++
      let lst = this.data.log_list
      this.setData({
        log_list: lst.concat(res)
      })
    }, res => {
      console.log('get_article_list failed: ', res)
    })
  },

  onClickArticle(e) {
    let articleId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../editor/person_log_show?article=' +  articleId + '&person=' + this.data.person + '&family=' + this.data.family
    })
  },

  tapAddArticle: function(e) {
    console.log('add article....')
    this.setData({
      showDialog: true,
      article_title_focus: true,
      article_title: ''
    })
  },

  OnArticleTitleInput(e) {
    this.data.article_title = e.detail.value
  },

  tapDialogButton(e) {
    if (e.detail.item.text == "新增") {
      let article_title = this.data.article_title.trim()
      if (article_title.length == 0) {
        app.showTip("文章标题不能为空")
        return
      } else if (article_title.length > 255) {
        app.showTip("文章标题不能超过255个字！")
        return
      }

      app.httpRequest('add_article_by_title', {
        family: this.data.family,
        target_person: this.data.person,
        title: article_title
      }, res => {
        console.log('add_article_by_title success: ', res)
        let articleId = res
        this.setData({
          showDialog: false,
          article_title_focus: false
        })
        wx.navigateTo({
          url: '../editor/edit_person_log?article=' + articleId + '&person=' + this.data.person
        })

      }, res => {
        console.log('add_article_by_title failed: ', res)

        this.setData({
          showDialog: false,
          article_title_focus: false
        })
      })

    } else {
      this.setData({
        showDialog: false,
        article_title_focus: false
      })
    }
  },

    //刷新单一文章的列表数据
    refreshSingleArticle(articleId) {
      app.httpRequest('get_single_article_in_list', {
        family: this.data.family,
        target_person: this.data.person,
        article: articleId
      }, res => {
        console.log('get_single_article_in_list success: ', res)
        //更新相应的文章项目
        let lst = this.data.log_list
        for (let i = 0; i < lst.length; i++) {
          if (lst[i].id == res.id) {
            lst[i] = res
          }
        }
        this.setData({
          log_list: lst
        })
  
      }, res => {
        console.log('get_single_article_in_list failed: ', res)
      })
    },
})